package com.association.main.frontcontroller;

import com.association.main.common.R;
import com.association.main.domain.*;
import com.association.main.dto.VoteDto;
import com.association.main.dto.VoteOptionDto;
import com.association.main.service.*;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front")
public class MyVoteController {

    @Autowired
    private VoteService voteService;

    @Autowired
    private VoteOptionService voteOptionService;

    @Autowired
    private VoteRecordService voteRecordService;

    @Autowired
    private JoinInfoService joinInfoService;

    @Autowired
    private ClubsService clubsService;

    @Autowired
    private UsersService usersService;

    @GetMapping("/votes/mylist")
    public R<Page<VoteDto>> myVotesList(@RequestParam(defaultValue = "1") int page, HttpServletRequest request) {
        // 分页查询投票
        Page<VoteDto> voteDtoPage = new Page<>(page, 10);
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getMemberId, userId);
        List<JoinInfo> joinInfoList = joinInfoService.list(joinInfoLambdaQueryWrapper);
        if(joinInfoList.size()>0){

        List<Integer> clubIds = joinInfoList.stream().map(JoinInfo::getClubId).collect(Collectors.toList());

// 构造查询条件
        LambdaQueryWrapper<Vote> voteLambdaQueryWrapper = new LambdaQueryWrapper<>();
        voteLambdaQueryWrapper.in(Vote::getClubId, clubIds);
        List<Vote> voteList = voteService.list(voteLambdaQueryWrapper);
// 构造返回的投票DTO列表
        List<VoteDto> voteDtoList = voteList.stream().map(vote -> {
            Clubs clubs = clubsService.getById(vote.getClubId());
            Users users=usersService.getById(vote.getUserId());
            VoteDto voteDto = new VoteDto(clubs.getName(), null, null, null,null);
            BeanUtils.copyProperties(vote, voteDto);
// 查询每个选项的投票记录数量
            List<VoteOptionDto> optionDtoList = new ArrayList<>();
            List<VoteOption> optionList = voteOptionService.list(new LambdaQueryWrapper<VoteOption>().eq(VoteOption::getVoteId, vote.getId()));
            for (VoteOption option : optionList) {
                VoteOptionDto optionDto = new VoteOptionDto();
                BeanUtils.copyProperties(option, optionDto);
                int voteCount = voteRecordService.count(new LambdaQueryWrapper<VoteRecord>().eq(VoteRecord::getVoteOptionId, option.getId()));
                optionDto.setVoteCount(voteCount);
                optionDtoList.add(optionDto);
            }
            voteDto.setOptions(optionDtoList);
            return voteDto;
        }).collect(Collectors.toList());

        voteDtoPage.setRecords(voteDtoList);
        voteDtoPage.setTotal(voteDtoList.size());
        }
        return R.success(voteDtoPage);
    }
    @GetMapping("/votes/getById")
    public R<List<VoteDto>> myVotesListById(int id, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        Vote voteById = voteService.getById(id);
        LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        //进行过滤，如果不在社团中，是不可以的
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getMemberId,userId);
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getClubId,voteById.getClubId());
        JoinInfo joinInfo = joinInfoService.getOne(joinInfoLambdaQueryWrapper);
        if (joinInfo == null) {
            return R.error("无加入社团");
        }
        Integer clubId = joinInfo.getClubId();
        Vote vote = voteService.getOne(new LambdaQueryWrapper<Vote>()
                .eq(Vote::getId, id)
                .eq(Vote::getClubId, clubId));
        if (vote == null) {
            return R.error("无投票信息");
        }
        List<VoteOptionDto> optionDtoList = new ArrayList<>();
        List<VoteOption> optionList = voteOptionService.list(new LambdaQueryWrapper<VoteOption>()
                .eq(VoteOption::getVoteId, vote.getId()));
        for (VoteOption option : optionList) {
            VoteOptionDto optionDto = new VoteOptionDto();
            BeanUtils.copyProperties(option, optionDto);
            int voteCount = voteRecordService.count(new LambdaQueryWrapper<VoteRecord>()
                    .eq(VoteRecord::getVoteOptionId, option.getId()));
            optionDto.setVoteCount(voteCount);
            optionDtoList.add(optionDto);
        }

        Clubs clubs = clubsService.getById(vote.getClubId());
        Users users = usersService.getById(vote.getUserId());
        VoteDto voteDto = new VoteDto(clubs.getName(), users.getName(), users.getEmail(), users.getPhone(),clubs.getLogo());
        BeanUtils.copyProperties(vote, voteDto);
        voteDto.setOptions(optionDtoList);
        return R.success(Collections.singletonList(voteDto));
    }
    @PostMapping("/votes/vote")
    public R<String> submitVote(@RequestBody VoteOption voteOption, HttpServletRequest request) {
        // 获取投票选项
        Integer voteOptionId = voteOption.getId();
        VoteOption option = voteOptionService.getById(voteOptionId);
        if (option == null) {
            return R.error("无此选项");
        }

        // 根据投票选项获取投票Vote
        Integer voteId = option.getVoteId();
        Vote vote = voteService.getById(voteId);
        if (vote == null) {
            return R.error("无此投票");
        }


        // 先检查投票自己是否在投票的club上
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        JoinInfo joinInfo = joinInfoService.getOne(new LambdaQueryWrapper<JoinInfo>()
                .eq(JoinInfo::getClubId, vote.getClubId())
                .eq(JoinInfo::getMemberId, userId));
        if (joinInfo == null) {
            return R.error("您不在此社团中");
        }

        // 检查投票是否已经截止
        if (vote.getEndTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() < System.currentTimeMillis()) {
            return R.error("投票已截止");
        }

        // 检查用户是否已经投过票
        // 检查用户是否已经投过票
        List<VoteOption> voteOptions = voteOptionService.list(new LambdaQueryWrapper<VoteOption>()
                .eq(VoteOption::getVoteId, voteId));
        for (VoteOption item : voteOptions) {
            boolean hasVoted = voteRecordService.count(new LambdaQueryWrapper<VoteRecord>()
                    .eq(VoteRecord::getVoteOptionId, item.getId())
                    .eq(VoteRecord::getMemberId, userId)) > 0;
            if (hasVoted) {
                return R.error("您已经投过票了");
            }
        }

        //步骤：查询出所有id为vote.id的voteOption
        //查询voteRecord是否有查询出的voteoption和memberId为userID
        //如果有，则说明投过票了

        // 创建投票记录
        VoteRecord voteRecord = new VoteRecord();
        voteRecord.setVoteOptionId(voteOptionId);
        voteRecord.setMemberId(userId);
        voteRecordService.save(voteRecord);
        return R.success("投票成功");
    }



}
